package net.huadong.decoder.length;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

/**
 * netty server端消息处理
 */
public class NettyLengthTimeServerHandler extends ChannelInboundHandlerAdapter {

    private int count=0;
    /**
     * 重写通道消息读取
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String)msg;
        System.out.println("服务端收到指令：" + body +"    计数："+ ++count);
        String res = null;
        if ("QUERY_TIME_ORDER".equals(body)) {
            res = new Date(System.currentTimeMillis()).toString();
        } else {
            res = "BAD ORDER";
        }

        ByteBuf resBuf = Unpooled.copiedBuffer(res.getBytes());
        ctx.writeAndFlush(resBuf);
    }

    /**
     * 通道读取完成事件
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 异常事件
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
